package com.xzz.tree;

/**
 * @author: hhz
 * @create: 2022-01-20 16:32
 * 110. 平衡二叉树
 **/
public class IsBalanced {
    public static void main(String[] args) {
        TreeNode node1 = new TreeNode(3);
        TreeNode node2 = new TreeNode(9);
        TreeNode node3 = new TreeNode(20);
        TreeNode node4 = new TreeNode(15);
        TreeNode node5 = new TreeNode(7);
        node1.left = node2;
        node1.right = node3;
        node3.left = node4;
        node3.right = node5;
        System.out.println(isBalanced(node1));
    }
    static boolean res = true;
    public static boolean isBalanced(TreeNode root) {
        maxDepth(root);
        return res;
    }
    public static int maxDepth(TreeNode root) {
        if(root==null){
            return 0;
        }
        int leftDepth = maxDepth(root.left);
        int rightDepth = maxDepth(root.right);
        int abs = Math.abs(leftDepth - rightDepth);
        if(abs>1){
            res = false;
        }
        return rightDepth>leftDepth?rightDepth+1:leftDepth+1;
    }
}
